//
//  DMGoodsDetailVC.m
//  DistributionMall
//
//  Created by JHnoplan on 2018/10/14.
//  Copyright © 2018年 JHnoplan. All rights reserved.
//

#import "DMGoodsDetailVC.h"
#import "DMGoodsDetailAppraiseVC.h"
#import "DMShareCodeVC.h"
#import "DMConfirmOrderVC.h"

//view
#import "DMGoodsIntroduceTableViewCell.h"
#import "DMGoodsDetailAppraiseCell.h"
#import "DMGoodsDetailHeadCell.h"
#import "SDCycleScrollView.h"
#import "ZYBannerView.h"
//model
#import "KStoreItemDetailModel.h"
#import "KStoreOrderModel.h"

//request
#import "KStoreRequest.h"

//other
#import "NSDate+Util.h"

//比例宏
#define KRealValue(value) ((value)/375.0f*[UIScreen mainScreen].bounds.size.width)

@interface DMGoodsDetailVC ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,ZYBannerViewDelegate,ZYBannerViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
//轮播图
@property (nonatomic,strong) ZYBannerView *bannerView;
@property (nonatomic, strong) NSMutableArray *dataArray;


//数据model
@property (nonatomic,strong) KStoreItemDetailModel * detailModel;
//数据model
@property (nonatomic,copy) NSString * webTextStr;

@end

@implementation DMGoodsDetailVC

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self startInit];
}

-(void)startInit {
    self.navigationItem.title = @"商品详情";
    _dataArray = [NSMutableArray new];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self setTableHeaderView];
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"DMGoodsDetailHeadCell" bundle:nil] forCellReuseIdentifier:@"DMGoodsDetailHeadCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DMGoodsDetailAppraiseCell" bundle:nil] forCellReuseIdentifier:@"DMGoodsDetailAppraiseCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DMGoodsIntroduceTableViewCell" bundle:nil] forCellReuseIdentifier:@"DMGoodsIntroduceTableViewCell"];
    
    //分享
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 30, 30);
    rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);
    [rightBtn setImage:[UIImage imageNamed:@"top_share"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(navRightClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    [self getDetail];

}

#pragma mark ----netWork---
-(void)getDetail{
    
    KStoreRequest * request = [[KStoreRequest alloc]initStoreItemDetailWithKey:self.key];
    
    MJWeakSelf
    [request newStartRequestWithCompletion:^(KBaseModel *baseModel) {
        
        KStoreItemDetailBaseModel * detailModel = [KStoreItemDetailBaseModel modelWithJSON:baseModel.data];
        weakSelf.detailModel = detailModel.saleEntityView;
        
        [weakSelf getItemexplainWithId:weakSelf.detailModel.descFid];
        [weakSelf.tableView reloadData];
        [weakSelf.bannerView reloadData];
    } failure:^(KBaseModel *errorModel) {
        
        [JLProgressHUDManager showErrorHud:errorModel.msg];
    }];
    
    
}

-(void)getItemexplainWithId:(NSString *)id{
    KStoreRequest * request = [[KStoreRequest alloc]initGetItemexplainWithKey:id];
    
    MJWeakSelf
    [request newStartRequestWithCompletion:^(KBaseModel *baseModel) {
        
        KStoreItemExplainBaseModel * exBaseModel = [KStoreItemExplainBaseModel modelWithJSON:baseModel.data];
        
        weakSelf.webTextStr = exBaseModel.glTextView.text;
        [weakSelf.tableView reloadSection:2 withRowAnimation:UITableViewRowAnimationNone];
    } failure:^(KBaseModel *errorModel) {
        
    }];
    
    
}
#pragma mark ----tableView---

//设置轮播图
-(void)setTableHeaderView{
    
    UIView * bannerView = [[UIView alloc]init];
    
    [bannerView addSubview:self.bannerView];
    
    [self.bannerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bannerView);
        make.left.right.equalTo(bannerView);
        make.height.equalTo(@KRealValue(200));
    }];
    
    [bannerView layoutIfNeeded];
    bannerView.height = CGRectGetMaxY(self.bannerView.frame);
    self.tableView.tableHeaderView = bannerView;
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return self.detailModel.saleReviewViews.count;
    }else{
        return 1;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

        self.tableView.rowHeight = UITableViewAutomaticDimension;
        self.tableView.estimatedRowHeight = 100;
        return self.tableView.rowHeight;

}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 35;
    }else if (section == 2) {
        
    }
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 35)];
        view.backgroundColor = DMWhiteColor;
        
        UILabel *titleLb = [UILabel new];
        titleLb.text = [NSString stringWithFormat:@"商品评价(%@)",self.detailModel.allReviewQty];
        titleLb.textColor = DMFontColor;
        titleLb.font = DMFontSize(14);
        [view addSubview:titleLb];
        [titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view);
            make.left.equalTo(view).offset(21);
            make.height.equalTo(@34);
        }];
        
        UIView *line = [[UIView alloc]init];
        line.backgroundColor = DMDefaultColor;
        [view addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(view);
            make.height.equalTo(@1);
        }];
        
        UIImageView *iv = [[UIImageView alloc]init];
        iv.image = [UIImage imageNamed:@"go_in"];
        [view addSubview:iv];
        [iv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view).offset(7);
            make.right.equalTo(view).offset(-15);
            make.width.height.equalTo(@20);
        }];
        
        UIButton *button = [UIButton new];
        [button setTitle:@"查看全部" forState:UIControlStateNormal];
        [button setTitleColor:DMMainColor forState:UIControlStateNormal];
        button.titleLabel.font = DMFontSize(14);
        button.backgroundColor = [UIColor clearColor];
        [button addTarget:self action:@selector(moreClick) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.bottom.equalTo(view);
            make.width.equalTo(@126);
        }];
        
        return view;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 8;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        DMGoodsDetailHeadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DMGoodsDetailHeadCell" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"DMGoodsDetailHeadCell" owner:self options:nil].firstObject;
        }
        
        cell.nameLb.text = self.detailModel.name;
        cell.priceLb.text = [NSString stringWithFormat:@"¥%@",self.detailModel.salePrice];
        cell.numLb.text = [NSString stringWithFormat:@"销量%@",self.detailModel.saleQty];
        cell.contentLb.text = self.detailModel.summary;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section == 1) {
        DMGoodsDetailAppraiseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DMGoodsDetailAppraiseCell" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"DMGoodsDetailAppraiseCell" owner:self options:nil].firstObject;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        KStoreItemDetailCommentModel * commentModel = self.detailModel.saleReviewViews[indexPath.row];
        
        cell.nameLb.text = commentModel.nickName;
        cell.contentLb.text = commentModel.content;
        cell.images = commentModel.saleReviewImgViews;
        cell.dateLb.text = [NSDate dateWithStrTimeInterval:commentModel.createTime fromatStr:@"yyyy-MM-dd hh:mm"];
        cell.starCount = commentModel.score.integerValue;
        return cell;
    }else{
        
        DMGoodsIntroduceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DMGoodsIntroduceTableViewCell" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"DMGoodsIntroduceTableViewCell" owner:self options:nil].firstObject;
        }
        
        if (self.webTextStr.length !=0 && cell.h5Str.length == 0) {
            cell.h5Str = self.webTextStr;

        }
        
        [cell setReloadBlock:^{
            [tableView reloadSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
        }];
        return cell;
    }
}

#pragma mark ----banner---


// 返回Banner需要显示Item(View)的个数
- (NSInteger)numberOfItemsInBanner:(ZYBannerView *)banner
{
    return self.detailModel.prodMediaViews.count;
}

// 返回Banner在不同的index所要显示的View
- (UIView *)banner:(ZYBannerView *)banner viewForItemAtIndex:(NSInteger)index
{
    KStoreItemDetailbannerModel * model = self.detailModel.prodMediaViews[index];
    UIImageView *imageView = [[UIImageView alloc]init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.cloudPath] placeholderImage:nil];
    return imageView;
}

#pragma mark ----action

//查看全部
-(void)moreClick {
    DMGoodsDetailAppraiseVC *vc = [DMGoodsDetailAppraiseVC new];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)navRightClick {
    DMShareCodeVC *vc = [DMShareCodeVC new];
    [self.navigationController pushViewController:vc animated:YES];
}
//立即购买
- (IBAction)buyClick:(UIButton *)sender {
    
    
    NSMutableArray * jsonArr = [NSMutableArray array];
    NSMutableDictionary * jsonDic = [NSMutableDictionary dictionary];
    [jsonDic setValue:@"1" forKey:@"qrty"];
    [jsonDic setValue:self.detailModel.defaultSkuId forKey:@"skuId"];
    [jsonArr addObject:jsonDic];
    
    NSString * jsonStr = [jsonArr jsonStringEncoded];
    
    KStoreRequest * request = [[KStoreRequest alloc]initStoreBuyNowWithSkuDataJson:jsonStr];
    [JLProgressHUDManager showLoadingHud];
    MJWeakSelf
    [request newStartRequestWithCompletion:^(KBaseModel *baseModel) {
        
        [JLProgressHUDManager hideHud];
        KStoreOrderModel * orderModel = [KStoreOrderModel modelWithJSON:baseModel.data];
        
        DMConfirmOrderVC *vc = [DMConfirmOrderVC new];
        vc.orderModel = orderModel;
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
        
    } failure:^(KBaseModel *errorModel) {
        [JLProgressHUDManager showErrorHud:errorModel.msg];
    }];
    
    

}

#pragma mark ----getting&setting

//轮播图
-(ZYBannerView *)bannerView{
    if (!_bannerView) {
        _bannerView = [[ZYBannerView alloc] initWithFrame:CGRectZero];
        _bannerView.delegate = self;
        _bannerView.dataSource = self;
        _bannerView.autoScroll = YES;
        _bannerView.shouldLoop = YES;
        _bannerView.pageControl.currentPageIndicatorTintColor = HEX_RGB(0x3197FA);
        _bannerView.pageControl.pageIndicatorTintColor = HEX_RGB(0xD8D8D8);
        [self.view addSubview:_bannerView];
    }
    return _bannerView;
}

@end
